package com.example.thread.d9CompletableFuture2.d2RunAsync;

import com.example.thread.d9CompletableFuture2.CommonUtils;

import java.util.concurrent.*;

// runAsync（）和supplyAsync（）方法都是开启单独的线程来执行异步任务
public class SupplyAsyncExecutorDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CommonUtils.printThreadLog("main start");

//        ExecutorService executor = Executors.newFixedThreadPool(4);
                ExecutorService executor = new ThreadPoolExecutor(
                3,
                5,
                8,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(4),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());   // 常用 AbortPolicy:丢弃任务并抛出异常，默认策略 ，CallerRunsPolicy:由主线程负责执行任务


        CompletableFuture<String> newsFuture = CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("异步任务开始");
            return CommonUtils.readFile("hello world");
        },executor);

        CommonUtils.printThreadLog("here not blocked main continue");
        String news = newsFuture.get(); // 方法执行到这里，会阻塞，等待多线程返回的结果
        System.out.println(news);

        executor.shutdown();

        CommonUtils.printThreadLog("main end");
    }
}
